#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include "debug.h"
#include "os_api.h"
#include "file_api.h"


#define _TASK_STACK_SIZE     1024*3
static void* _task_stack = NULL;
static OSTaskRef _task_ref = NULL;
static OSFlagRef _flag_ref = NULL;
static OSATimerRef _timer_ref = NULL;

#define TASK_TIMER_CHANGE_FLAG_BIT    0x01
#define TASK_TIMER_CHANGE2_FLAG_BIT    0x02

static int count = 0;

static void _timer_callback(UINT32 param)
{
    LOG_PRINTF("debug> count = %d",++count);
    int temp;
    temp = count %2 +1;

    if (temp & 0x01) {
        OSAFlagSet(_flag_ref, TASK_TIMER_CHANGE2_FLAG_BIT, OSA_FLAG_OR);
    } else {
        OSAFlagSet(_flag_ref, TASK_TIMER_CHANGE_FLAG_BIT, OSA_FLAG_OR);
    }
}

static void _task(void *ptr)
{
	int ret;
    fatTYPE_stat stat;
	
    OSA_STATUS status;
    UINT32 flag_value;
    UINT32 flag_mask = TASK_TIMER_CHANGE_FLAG_BIT | TASK_TIMER_CHANGE2_FLAG_BIT;
    int fd = 0;
    char temp[30];

    while(1) {
        status = OSAFlagWait(_flag_ref, flag_mask, OSA_FLAG_OR_CLEAR, &flag_value, OSA_SUSPEND);
		ASSERT(status == OS_SUCCESS);
        LOG_PRINTF("debug> count = %d",count);
        if (flag_value & TASK_TIMER_CHANGE_FLAG_BIT) {
			ret=FDI_Stat((char *)"test_file",&stat);
			if(ret!=0){
				LOG_PRINTF("test_file is not exist\n");
			}else{
				LOG_PRINTF("test_file size is %d\n", stat.st_size);
			}
		
            fd = FDI_fopen("test_file", "wb");
            if (fd != 0){
                LOG_PRINTF("debug> open file for write OK\n");
                memset(temp, 0, 30);
                sprintf(temp,"Hello world! _%d",count);
                FDI_fwrite(temp, 20, 1, fd);
                FDI_fclose(fd);
            } else {
                LOG_PRINTF("debug> open file for write error\n");
            }
        } else if (flag_value & TASK_TIMER_CHANGE2_FLAG_BIT) {
            fd = FDI_fopen("test_file", "rb");
            if (fd) {
                LOG_PRINTF("debug> open file for read OK\n");
                memset(temp,0,30);
                FDI_fread(temp,30,1,fd);
                FDI_fclose(fd);
                LOG_PRINTF("debug> temp = %s", temp);
            } else {
                LOG_PRINTF("debug> open file for read error\n");
            }
        }
    }
}


int main(void)
{
    int ret;
    LOG_PRINTF("debug> enter main\n");
    
    ret = OSAFlagCreate(&_flag_ref);
    ASSERT(ret == OS_SUCCESS);
    ret = OSATimerCreate(&_timer_ref);
    ASSERT(ret == OS_SUCCESS);
	
    _task_stack = malloc(_TASK_STACK_SIZE);
    ASSERT(_task_stack != NULL);
	
    ret = OSATaskCreate(&_task_ref, _task_stack, _TASK_STACK_SIZE, 100, "filetest-task", _task, NULL);
    ASSERT(ret == OS_SUCCESS);
    OSATimerStart(_timer_ref, 10 * 200, 10 * 200, _timer_callback, 0); // 10 seconds timer
    
    return 0;
}

